<template>
  <div class="contain">
    <el-card header="请先登录">
      <el-form :model="model" @submit.native.prevent="login">
        <el-form-item label="用户名">
          <el-input v-model="model.username"></el-input>
        </el-form-item>

        <el-form-item label="密码">
          <el-input v-model="model.password"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" native-type="submit">登录</el-button>
          <el-button type="primary" @click="showRegister">注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 注册对话框 -->
    <el-dialog title="自助注册：" :visible.sync="dialogVisible" width="30%">
      <el-form :model="reg">
        <el-form-item label="用户名">
          <el-input v-model="reg.username"></el-input>
        </el-form-item>

        <el-form-item label="密码">
          <el-input v-model="reg.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" disabled @click="register">注册</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      model: {},
      dialogVisible: false,
      reg: {},
    };
  },
  methods: {
    async login() {
      const res = await this.$http.post("login", this.model);
      window.sessionStorage.setItem("token", res.data);
      this.$router.push("/main");
    },
    showRegister() {
      this.dialogVisible = !this.dialogVisible;
    },
    async register() {
      const res = await this.$http.post("register", this.reg);
      this.$message({
        type: "success",
        message: "注册成功",
      });
      this.dialogVisible = !this.dialogVisible;
    },
  },
  created() {},
};
</script>

<style lang="scss">
.contain {
  width: 30rem;
  margin: 10rem auto;
  .register {
    margin-left: 50px;
  }
}
</style>